package com.jysz.certificate.web.action.system;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.jysz.certificate.action.AbstractBaseAction;
import com.jysz.certificate.constant.OperCodeConstant;
import com.jysz.certificate.persistence.enums.OrganizationEnum;
import com.jysz.certificate.persistence.enums.PostType;
import com.jysz.certificate.persistence.model.dto.UserDTO;
import com.jysz.certificate.persistence.model.system.Organization;
import com.jysz.certificate.persistence.model.system.Role;
import com.jysz.certificate.persistence.model.system.Shop;
import com.jysz.certificate.persistence.model.system.User;
import com.jysz.certificate.service.system.OrganizationService;
import com.jysz.certificate.service.system.RoleService;
import com.jysz.certificate.service.system.ShopService;
import com.jysz.certificate.service.system.UserService;
import com.jysz.certificate.utils.CommonUtil;
import com.jysz.certificate.web.action.Excel.ExcelSheetParser;
import com.jysz.webcore.ssh.annotation.PermissionPoint;

@Controller
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Namespace("/system/user")
public class UserAction extends AbstractBaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Resource
	private UserService userService;
	@Resource
	private ShopService shopService;
	@Resource
	private OrganizationService organizationService;

	private User us;
	private UserDTO search;
	private File file;
	private Date newDate;
	private int post;
	private String pageIds;
	private String allIds;

	@Action("importUser")
	@PermissionPoint(point=OperCodeConstant.SYS_USER_IMPORT)
	public String importUser() throws Exception {
		boolean mark = true;
		List<User> listUsers = new ArrayList<User>();
		
		Map<String, Shop> shopMap = shopService.getAllshop();//获得所有的4S店
		Map<String, Organization> organMap = organizationService.DomainMap(OrganizationEnum.SHOP);//获得组织架构上的经销店
		Map<String, User> userMap = userService.userMap();
		
		try {
			ExcelSheetParser parser = new ExcelSheetParser(file);
			List<List> datas = parser.getDatasInSheet(0);
			List listB = datas.get(0);
			String table = "ID,姓名,密码,角色,Email,联系方式,性别,经销店,状态";
			String[] ta = table.split(",");
			for (int i = 0; i < listB.size(); i++) {
				if (ta.length + 1 != listB.size()) {
					this.addActionError("文件不匹配，请确认导入文件是店铺文件\n");
					mark = false;
					break;
				}
				if (i != listB.size() - 1) {
					String values = String.valueOf(listB.get(i));
					if (!ta[i].equals(values)) {
						this.addActionError("第1行，第" + (i + 1)+ "列,  "+values+"  导入文件表头存在错误\n");
						mark = false;
						break;
					}
				}
			}
			
			if(mark){
				for(int i=1;i<datas.size();i++){//显示数据
					List row = datas.get(i);
					User user = new User();
					   for(int j=0;j<row.size()-1;j++){
						   String valueString=String.valueOf(row.get(j));
						   valueString = valueString.trim();
						   if(j==0 && !valueString.equals("null")){//工号 账号
							   if(userMap.containsKey(valueString)){
								   this.addActionError("第" + ( i + 1 ) + "行，第" + (j+1)+"列," + valueString + "：此工号系统中已存在,或者在excel已重复添加\n");
								   mark = false;
								   continue;
							   }else{
								   user.setJobNumber(valueString);
								   user.setName(valueString);
								   userMap.put(valueString, user);
							   }
							   
						   }else if(j==1 && !valueString.equals("null")){//姓名
							   user.setRealName(valueString);
						   }else if(j==2&& !valueString.equals("null")){//密码
							   user.setPassword(valueString);
						   }else if(j==3&& !valueString.equals("null")){//角色
							   if(PostType.Shop.getName().equals(valueString)){
								   PostType postType =PostType.indexName(valueString);
									if(null != postType){
										 user.setPost(postType);
									}else{
										  this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,"+valueString+"：请核对用户角色\n");
										   mark = false;
										   continue;
									}
							   }else{
								   this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,"+valueString+"：用户导入只支持"+PostType.Shop.getName()+"其他角色用户请手工添加\n");
								   mark = false;
								   continue;
							   }
								
							 
						   }else if(j==4){//Email
							   if(valueString.equals("null")){
								   user.setEmail(null);
							   }else{
								   user.setEmail(valueString);
							   }
							  
						   }else if(j==5){//手机
							   if(!valueString.equals("null") && valueString != null){
								   if(isMobileNO(valueString)||isTelephone(valueString)){
									   user.setTelephone(valueString);
								   }else{
									   this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,联系方式："+valueString+"  格式不正确\n");
									   mark = false;
									   continue;
								   }
								   
							   }else{
								   user.setTelephone(null);
							   }
							  
							   
						   }else if(j==6&& !valueString.equals("null")){//性别
							   if(valueString.trim().equals("男") || valueString.trim().equals("女")){
								   user.setSex(valueString);
							   }else {
								   this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,"+valueString+"：请核对性别\n");
								   mark = false;
								   continue;
							   }
								   
							   
						   }else if(j==7){//TODO 经销店
							   if(!valueString.equals("null")){
								   valueString  = valueString.toUpperCase();
								   if(shopMap.containsKey(valueString)){
									   Shop shop = shopMap.get(valueString);
									   if(organMap.containsKey(shop.getShopName())){
										   user.setShop(shop);
									   }else{
										   this.addActionError("第"+(i+1)+"行  ,"+valueString+"：不存在组织架构中\n");
										   mark = false;
										   continue;
									   }
								   }else{
									   this.addActionError("第"+(i+1)+"行   "+valueString+"：不存在系统中\n");
									   mark = false;
									   continue;
								   } 
							   }else{
								   user.setShop(null);
							   }
								   
							   
						   } else if(j==8&& !valueString.equals("null")){//状态
							   if(valueString.trim().equals("禁用")){
								   user.setLocked("1");
							   }else if(valueString.trim().equals("激活")){
								   user.setLocked("0");
							   }else{
								   this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,"+valueString+"：请核对状态数据      1:禁用    0:激活  请填写中文\n");
								   mark = false;
								   continue;
							   }
							   
						   }else {//
							   this.addActionError("第"+(i+1)+"行，第"+(j+1)+"列,"+valueString+"：数据不能为空，请核对\n");
							   mark = false;
							   continue;
						   }
						   
					   }
					   if(mark){
						   
						   listUsers.add(user);
					   }
				}
				
			}
			if(mark){
				for(int i=0;i<listUsers.size();i++){
					User user = listUsers.get(i);
					for(int j=0;j<listUsers.size();j++){
						User us = listUsers.get(j);
						if(i != j){
							if(user.getJobNumber().equals(us.getJobNumber()) && user.getRealName().equals(us.getRealName()) && user.getShop().getShopMark().equals(us.getShop().getShopMark())){
								this.addActionError(us.getRealName()+"：存在相同的店\n");
								mark =false;
							}
							if(user.getJobNumber().equals(us.getJobNumber()) && !user.getRealName().equals(us.getRealName())){
								this.addActionError(user.getRealName()+"与"+us.getRealName()+"：工号相同\n");
								mark =false;
							}
						}
						
					}
				}
			}
		
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("文件没找到 : " + e);
		} catch (IOException e) {
			e.printStackTrace();
			this.addActionError("文件不匹配, 请确认导入文件是合格证导入文件\n");
			mark = false;
		}
		if(mark){
			Map<String, User> uMap = new HashMap<String, User>();
			for(User user : listUsers){
				if(uMap.containsKey(user.getJobNumber())){
					User us = uMap.get(user.getJobNumber());
					if(null != user.getShop()){
						Organization organization = organMap.get(user.getShop().getShopName());
						   Organization organiz =new Organization();
						   organiz.setObjectId(us.getId());
						   organiz.setParent(organization);
						   organiz.setName(us.getRealName());
						   organiz.setType(OrganizationEnum.STAFF);
						   
						   int maxOrder = organizationService.getMaxOrder(organization.getId());
						   organiz.setOrder(maxOrder + 1);
						   organiz.setCode(organizationService.genCode(organization, maxOrder));
						   organiz.setGrade(organization.getGrade()+1);
						   organization.getChilds().add(organiz);
						   organizationService.save(organization);
					}
					
					
				}else{
					userService.save(user);
					if(user.getId()!= null){
						if(null != user.getShop()){
							Organization organization = organMap.get(user.getShop().getShopName());
							   Organization organiz =new Organization();
							   organiz.setObjectId(user.getId());
							   organiz.setParent(organization);
							   organiz.setName(user.getRealName());
							   organiz.setType(OrganizationEnum.STAFF);
							   
							   int maxOrder = organizationService.getMaxOrder(organization.getId());
							   organiz.setOrder(maxOrder + 1);
							   organiz.setCode(organizationService.genCode(organization, maxOrder));
							   organiz.setGrade(organization.getGrade()+1);
							   organization.getChilds().add(organiz);
							   organizationService.save(organization);
						}
						 
					}
					uMap.put(user.getJobNumber(), user);
				}
			}
			setSuccessPopMessage("数据导入成功！");
			setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search",
					search);
			return SHOW_MSG_PAGE;
		}else{
			return "tolead";
		}
	}

	@Action("toUpdate")
	@PermissionPoint(point=OperCodeConstant.SYS_USER_EDIT)
	public String toUpdate() {
		us = userService.finUserById(us.getId());
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search",
				search);
		return "update";
	}
	
	@Resource
	private RoleService roleService;
	
	@Action("update")
	@PermissionPoint(point=OperCodeConstant.SYS_USER_EDIT)
	public String update() {
		PostType type = PostType.index(post);
		User user = userService.finUserById(us.getId());
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search",search);
		if(!user.getPost().equals(type)&&!organizationService.getUpdateUser(us.getId())){
			setSuccessPopMessage("该用户在组织架构中存在，请先从组织架构中移除。。。");
		}else if(userService.getPassUserByJobNumber(us)!=null){
				msgMap = new HashMap();
				msgMap.put("jobNumber", "工号已存在");
				return "update";
		}else{
			User userCopy = userService.find(us.getId());
			//删除角色
			if(userCopy.getPost().equals(PostType.Shop)||userCopy.getPost().equals(PostType.Manager)||userCopy.getPost().equals(PostType.Responsible)){
				Role role = new Role();
				if(userCopy.getPost().equals(PostType.Shop)){
					role = roleService.find(1L);
				}
				if(userCopy.getPost().equals(PostType.Manager)){
					role = roleService.find(2L);
				}
				if(userCopy.getPost().equals(PostType.Responsible)){
					role = roleService.find(3L);
				}
				Set<User> set = role.getUsers();
				set.remove(userCopy);
				roleService.save(role);
			}
			us.setPost(PostType.index(post));
			//添加角色
			if(us.getPost().equals(PostType.Shop)||us.getPost().equals(PostType.Manager)||us.getPost().equals(PostType.Responsible)){
				Role role = new Role();
				if(us.getPost().equals(PostType.Shop)){
					role = roleService.find(1L);
				}
				if(us.getPost().equals(PostType.Manager)){
					role = roleService.find(2L);
				}
				if(us.getPost().equals(PostType.Responsible)){
					role = roleService.find(3L);
				}
				Set<User> set = role.getUsers();
				set.add(us);
				roleService.merge(role);
			}
			String ary[]=new String[]{"id","createdAt","creator","roles"};
			BeanUtils.copyProperties(us,userCopy, ary);
			userService.updateUser(userCopy);
			setSuccessPopMessage("用户修改成功");
		}
		return SHOW_MSG_PAGE;
	}

	private String shopIds;
	public String getShopIds() {
		return shopIds;
	}

	public void setShopIds(String shopIds) {
		this.shopIds = shopIds;
	}

	@Action("add")
	@PermissionPoint(point=OperCodeConstant.SYS_USER_ADD)
	public String add() {
		us.setPost(PostType.index(post));
		if(userService.getUserByName(us.getName())!=null){
			msgMap = new HashMap();
			msgMap.put("name", "账号已存在");
			return "add";
		}else{
			setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search",
					search);
			userService.saveUser(us);
			if(us.getPost().equals(PostType.Shop)||us.getPost().equals(PostType.Manager)||us.getPost().equals(PostType.Responsible)){
				Role role = new Role();
				if(us.getPost().equals(PostType.Shop)){
					role = roleService.find(1L);
				}
				if(us.getPost().equals(PostType.Manager)){
					role = roleService.find(2L);
				}
				if(us.getPost().equals(PostType.Responsible)){
					role = roleService.find(3L);
				}
				Set<User> set = role.getUsers();
				set.add(us);
				roleService.save(role);
			}
			if(shopIds!=null&&!"".equals(shopIds)){
				String[] ids = shopIds.indexOf(",")>-1?shopIds.split(","):new String[]{shopIds};
				for (int i = 0; i < ids.length; i++) {
					Organization org = organizationService.getOrg(new Long(ids[i]));
					Organization orgUser = new Organization();
					orgUser.setParent(org);
					orgUser.setType(OrganizationEnum.STAFF);
					orgUser.setOrder(organizationService.getMaxOrder(org.getId()) + 1);
					orgUser.setCode(organizationService.genCode(org.getId()));
					orgUser.setName(us.getRealName());
					orgUser.setGrade(org.getGrade() + 1);
					orgUser.setObjectId(us.getId());
					organizationService.save(orgUser);
				}
				setSuccessPopMessage("新增用户成功,并且已经加入到组织架构中.");
			}else{
				setSuccessPopMessage("新增用户成功");
			}
			
		}
		return SHOW_MSG_PAGE;
	}

	@Action(INDEX)
	public String index() {
		this.setPage(userService.selectUser(search, getCurrentPage(),
				getPageSize()));
		return "index";
	}

	@Action("delete")
	@PermissionPoint(point=OperCodeConstant.SYS_USER_DEL)
	public String delete() {
		userService.deleteUser(us);
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search",
				search);
		setSuccessPopMessage("删除用户成功");
		return SHOW_MSG_PAGE;
	}

	@Action("toAdd")
	@PermissionPoint(point=OperCodeConstant.SYS_USER_ADD)
	public String toAdd() {
		setRedirectUrl("index.do?currentPage=" + getCurrentPage(), "search",
				search);
		this.newDate = new Date();
		return "add";
	}

	@Action("choose")
	public String choose() {
		setPage(userService.choose(us, getCurrentPage(), getPageSize()));
		return "choose";
	}
	
	@Action("chooseUser")
	public String chooseUser() {
		setPage(userService.chooseUser(us, post,getCurrentPage(), 10));
		List<User> list=(List<User>) getPage().getResult();
		List<Long> all= CommonUtil.getLongList(allIds);
		List<Long> page= new ArrayList<Long>();
		if(list!=null&&all!=null){
			for(User u:list){
				if(all.contains(u.getId())){
					all.remove(u.getId());
					page.add(u.getId());
				}
			}
			StringBuilder sb=new StringBuilder();
			for(Long tmp:all){
				sb.append(tmp).append(",");
			}
			allIds=sb.toString();
		}
		
		if(list!=null&&page!=null){
			StringBuilder sb=new StringBuilder();
			for(Long tmp:page){
				sb.append(tmp).append(",");
			}
			pageIds=sb.toString();
			sb=null;
		}
		
		return "chooseUser";
	}
	
	@Action("chooseMulti")
	public String chooseMulti() {
		setPage(userService.choose(us, getCurrentPage(), 10));
		List<User> list=(List<User>) getPage().getResult();
		List<Long> all= CommonUtil.getLongList(allIds);
		List<Long> page= new ArrayList<Long>();
		if(list!=null&&all!=null){
			for(User u:list){
				if(all.contains(u.getId())){
					all.remove(u.getId());
					page.add(u.getId());
				}
			}
			StringBuilder sb=new StringBuilder();
			for(Long tmp:all){
				sb.append(tmp).append(",");
			}
			allIds=sb.toString();
		}
		
		if(list!=null&&page!=null){
			StringBuilder sb=new StringBuilder();
			for(Long tmp:page){
				sb.append(tmp).append(",");
			}
			pageIds=sb.toString();
			sb=null;
		}
		
		return "chooseMulti";
	}
	
	@Action("getUserNames")
	public String getUserNames(){
		
		setJsonMsg(null, true, userService.getUserNames(allIds));
		return JSON_PAGE;
	}
	
	@Action("opneImport")
	@PermissionPoint(point=OperCodeConstant.SYS_USER_IMPORT)
	public String opneImport() {
		setPage(userService.choose(us, getCurrentPage(), getPageSize()));
		return "tolead";
	}
	public User getUs() {
		return us;
	}

	public void setUs(User us) {
		this.us = us;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public UserDTO getSearch() {
		return search;
	}

	public void setSearch(UserDTO search) {
		this.search = search;
	}

	public Date getNewDate() {
		return newDate;
	}

	public void setNewDate(Date newDate) {
		this.newDate = newDate;
	}

	public int getPost() {
		return post;
	}

	public void setPost(int post) {
		this.post = post;
	}

	public String getPageIds() {
		return pageIds;
	}

	public void setPageIds(String pageIds) {
		this.pageIds = pageIds;
	}

	public String getAllIds() {
		return allIds;
	}

	public void setAllIds(String allIds) {
		this.allIds = allIds;
	}
	private Map msgMap;

	public Map getMsgMap() {
		return msgMap;
	}

	public void setMsgMap(Map msgMap) {
		this.msgMap = msgMap;
	}
	/**
	 * 
	 * @param phonenumber
	 * @return
	 */
	public static boolean isTelephone(String phonenumber) {
        String phone = "0\\d{2,3}-\\d{7,8}";
        Pattern p = Pattern.compile(phone);
        Matcher m = p.matcher(phonenumber);
        return m.matches();
    }

    // 判断手机号
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

}
